{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# UserCF算法\n",
    "import numpy as np\n",
    "import scipy.spatial.distance as ssd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 用户特征向量\n",
    "r1 = np.array([1,4,2,1])\n",
    "r2 = np.array([2,4,2,1])\n",
    "r3 = np.array([5,1,5,4])\n",
    "r4 = np.array([2,5,3,4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# pearson相关系数\n",
    "def sim(v1,v2):\n",
    "    # 平均分数\n",
    "    v1_mu = sum(v1) / len(v1)\n",
    "    v2_mu = sum(v2) / len(v2)\n",
    "    # 特征向量去均值\n",
    "    v1_ = v1 - v1_mu\n",
    "    v2_ = v2 - v2_mu\n",
    "    return 1 - ssd.cosine(v1_,v2_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "用户1,2的相似度： 0.936585811581694\n",
      "用户1,3的相似度： -0.8716019289105665\n",
      "用户1,4的相似度： 0.7302967433402214\n"
     ]
    }
   ],
   "source": [
    "# 计算相关系数\n",
    "sim1_2 = sim(r1,r2)\n",
    "sim1_3 = sim(r1,r3)\n",
    "sim1_4 = sim(r1,r4)\n",
    "print(\"用户1,2的相似度：\",sim1_2)\n",
    "print(\"用户1,3的相似度：\",sim1_3)\n",
    "print(\"用户1,4的相似度：\",sim1_4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.0 2.25 3.75 3.5\n",
      "预测分数是： 4.047032197970447\n"
     ]
    }
   ],
   "source": [
    "r1_mu = sum(r1) / len(r1)\n",
    "r2_mu = sum(r2) / len(r2)\n",
    "r3_mu = sum(r3) / len(r3)\n",
    "r4_mu = sum(r4) / len(r4)\n",
    "print(r1_mu,r2_mu,r3_mu,r4_mu)\n",
    "predict_rating = r1_mu + ((5 - r2_mu) * sim1_2 + (2 - r3_mu) * sim1_3 + (5 - r4_mu) * sim1_4) / (np.abs(sim1_2) + np.abs(sim1_3) + \n",
    "                                                                                               np.abs(sim1_4))\n",
    "print('预测分数是：',predict_rating)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最终预测打分： 4.047032197970447\n"
     ]
    }
   ],
   "source": [
    "predict_rating = np.clip(predict_rating,0,5)  # 设置分数范围\n",
    "print('最终预测打分：',predict_rating)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>item1</th>\n",
       "      <th>item2</th>\n",
       "      <th>item3</th>\n",
       "      <th>item4</th>\n",
       "      <th>item5</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>user1</th>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>user2</th>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>user3</th>\n",
       "      <td>5</td>\n",
       "      <td>1</td>\n",
       "      <td>5</td>\n",
       "      <td>4</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>user4</th>\n",
       "      <td>2</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "       item1  item2  item3  item4  item5\n",
       "user1      1      4      2      1      0\n",
       "user2      2      4      2      1      5\n",
       "user3      5      1      5      4      2\n",
       "user4      2      5      3      4      5"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# itemCF算法\n",
    "import pandas as pd\n",
    "df_data = pd.read_csv('D:/test_data1.csv',sep=',')\n",
    "df_data.index = ['user1','user2','user3','user4']\n",
    "df_data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2.8, 3.4, 3.8]"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# user2到user4的平均向量\n",
    "user_mu = [\n",
    "    sum(df_data.loc[index]) / len(df_data.loc[index])\n",
    "    for index in df_data.iloc[1:4].index\n",
    "]\n",
    "user_mu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-0.84561791,  0.88176419, -0.88176419, -0.83262711])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def sim(v1,v2):\n",
    "    # 特征向量去均值\n",
    "    v1_ = v1 - user_mu\n",
    "    v2_ = v2 - user_mu\n",
    "    return 1 - ssd.cosine(v1_,v2_)\n",
    "sim_v = np.array(\n",
    "   [ sim(df_data['item5'][1:4],df_data[item][1:4])\n",
    "     for item in ['item1','item2','item3','item4']\n",
    "    ]\n",
    ")\n",
    "sim_v"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.024778902847947197\n"
     ]
    }
   ],
   "source": [
    "predict_rating = np.dot(sim_v,df_data.iloc[0][0:4]) / sum(np.abs(sim_v))\n",
    "print(predict_rating)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### userCF和itemCF算法对比\n",
    "1. ItemCF算法的预测结果比UserCF算法结果略高\n",
    "2. ItemCF可以预先算好各个物品的相似度，预测速度快\n",
    "3. 如果物品的变更速度快，物品相似度的矩阵频繁更新需要的代价太大，使用UserCF，例如新闻网站"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n",
      "[[1 2]\n",
      " [3 4]]\n",
      "b\n",
      "[[5 6]\n",
      " [7 8]]\n"
     ]
    }
   ],
   "source": [
    "# numpy实现矩阵内积\n",
    "a=np.array([[1,2],[3,4]])\n",
    "b=np.array([[5,6],[7,8]])\n",
    "print(\"a\")\n",
    "print(a)\n",
    "print(\"b\")\n",
    "print(b)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "矩阵内积结果为：\n",
      "[[17 23]\n",
      " [39 53]]\n"
     ]
    }
   ],
   "source": [
    "d=np.inner(a,b)\n",
    "print(\"矩阵内积结果为：\")\n",
    "print(d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
